<template>
  <div>
    <NavBar>
      {{ type == 'add' ? '添加地址' : '编辑地址' }}
    </NavBar>
    <div class="address-edit">
      <van-address-edit :area-list="areaList" :show-delete="type == 'edit' ? true : false" show-set-default show-search-result
        :address-info="addressInfo" :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave" @delete="onDelete" @change-detail="onChangeDetail" />
    </div>
  </div>
</template>

<script>
import areaList from '@/utills/address'
import { Toast } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { reactive, toRefs, onMounted, getCurrentInstance, ref } from 'vue'
export default {
  name: "addressEdit",
  setup() {
    const { proxy } = getCurrentInstance()
    const router = useRouter()
    const route = useRoute()
    let type = ref('add')
    const state = reactive({
      areaList: areaList,
      searchResult: [],
      addressInfo: {}
    })
    const onSave = async (val) => {
      const params = {
        name: val.name,
        phone: val.tel,
        province: val.province,
        city: val.city,
        county: val.county,
        address: val.addressDetail,
        is_default: val.isDefault ? 0 : 1
      }
      if (route.query.type == 'edit') {
        proxy.$API.address.editAddress(route.query.addressId, params).then(res => {
          if (res.status == 204) {
            router.back()
            Toast('修改地址成功')
          }
        })
      } else {
        await proxy.$API.address.addAddress(params).then(res => {
          if (res.status == 201) {
            router.back()
            Toast('添加地址成功')
          }
        })
      }
    }
    const onDelete = () => {
      proxy.$API.address.DeleteAddress(route.query.addressId).then(res => {
        if (res.status == 204) {
          router.back()
          Toast('删除订单成功')
        }
      })
    }
    const onChangeDetail = () => {

    }
    onMounted(() => {
      if (route.query.type == 'edit') {
        type.value = 'edit'
        proxy.$API.address.getAddressDetail(route.query.addressId).then(res => {
          state.addressInfo = {
            name: res.name,
            tel: res.phone,
            province: res.province,
            city: res.city,
            county: res.county,
            addressDetail: res.address,
            isDefault: res.is_default ? 1 : 0
          }
        })
      }
    })
    return {
      ...toRefs(state),
      onChangeDetail,
      onSave,
      onDelete,
      type
    }
  }
}
</script>

<style scoped>
.address-edit {
  margin-top: 45px;
}
</style>
